package server

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/transport"
	v1 "kratos-shop/api/helloworld/v1"
	"kratos-shop/internal/conf"
	"kratos-shop/internal/service"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/transport/http"
)

// MiddlewareDemo 实现自定义的中间件
func MiddlewareDemo() middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (interface{}, error) {
			fmt.Println("中间件执行之前................")
			// 比如，我们想要从请求头中，拿到 token
			if tr, ok := transport.FromClientContext(ctx); ok {
				token := tr.RequestHeader().Get("token")
				fmt.Printf("token is: %v\n", token)
			}
			defer func() {
				fmt.Println("中间件执行之后...........")
			}()
			return handler(ctx, req)
		}
	}
}

// NewHTTPServer new an HTTP server.
func NewHTTPServer(c *conf.Server, greeter *service.GreeterService, logger log.Logger) *http.Server {
	var opts = []http.ServerOption{
		http.Middleware(
			recovery.Recovery(),
			MiddlewareDemo(),
		),
		//添加注入自定义的返回类型
		http.ResponseEncoder(responseEncode),
		http.ErrorEncoder(errEncoder),
	}
	if c.Http.Network != "" {
		opts = append(opts, http.Network(c.Http.Network))
	}
	if c.Http.Addr != "" {
		opts = append(opts, http.Address(c.Http.Addr))
	}
	if c.Http.Timeout != nil {
		opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
	}
	srv := http.NewServer(opts...)
	v1.RegisterGreeterHTTPServer(srv, greeter)
	return srv
}
